package com.example.yangzhifu.myapplication;

import android.app.Activity;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.PictureDrawable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import org.apache.batik.transcoder.TranscoderException;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

public class MainActivity extends AppCompatActivity {
    private static final String TAG ="MYTAG";
    private Button button;
    private ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        verifyStoragePermissions(this);
        button = (Button) findViewById(R.id.btConvert);
        imageView = (ImageView) findViewById(R.id.image);
       // execRootCmdSilent("export CLASSPATH=/system/framework/test.jar");
       // execRootCmdSilent("exec app_process /system/bin Solution.Solution");
        init();
    }

    private void init() {
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                final String svgCode;
//                svgCode=getFromAssets("test.svg");
//                //svgCode=readToString("/sdcard/test/test.svg");// 更改svg文件中的width和height ,可以最终改变导出的png图片的大小
//                final String pngFilePath = "/sdcard/test/test.png";
//                System.out.println(svgCode);
//
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            try {
//
//                                BitmapHelper.convertToPng(svgCode.toString(), pngFilePath);
//                            }catch (Exception e){
//
//                            }
//                        }
//                    });



               // execRootCmdSilent("export CLASSPATH=/system/framework/test.jar");
               // execRootCmdSilent("exec app_process /system/bin Solution.Solution");

                String string = getFromAssets("test.svg");
                try {
                    //  BitmapHelper.convertToPng(string,"path");
                    SVG svg = new SVGBuilder().readFromAsset(getAssets(), "test.svg").build();
                    //拿到svg图片的drawable
                    PictureDrawable drawable = svg.getDrawable();

                    //图片背景的画笔
                    Paint paint = new Paint();
                    paint.setColor(Color.WHITE);
                    //图片线条的画笔
                    Paint paint1 = new Paint();
                    paint1.setColor(Color.BLACK);
                    //创建bitmap对象
                    Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
                    Canvas canvas = new Canvas(bitmap);
                    canvas.drawRect(0, 0, bitmap.getWidth() + 50, bitmap.getHeight() + 50, paint);
                   drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
                    drawable.draw(canvas);
                    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                    imageView.setScaleType(ImageView.ScaleType.FIT_START);
                    imageView.setImageDrawable(drawable);
                    FileOutputStream fos = new FileOutputStream(new File("/sdcard/test/test6.png"));
                    //转为jpg格式并写入到sd卡
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
                    fos.flush();
                    fos.close();


                } catch (Exception e) {

                }
            }
        });
    }

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE" };


    public static void verifyStoragePermissions(Activity activity) {

        try {
            //检测是否有写的权限
            int permission = ActivityCompat.checkSelfPermission(activity,
                    "android.permission.WRITE_EXTERNAL_STORAGE");
            if (permission != PackageManager.PERMISSION_GRANTED) {
                // 没有写的权限，去申请写的权限，会弹出对话框
                ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,REQUEST_EXTERNAL_STORAGE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String readToString(String fileName) {
        String encoding = "UTF-8";
        File file = new File(fileName);
        Long filelength = file.length();
        byte[] filecontent = new byte[filelength.intValue()];
        try {
            FileInputStream in = new FileInputStream(file);
            in.read(filecontent);
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            return new String(filecontent, encoding);
        } catch (UnsupportedEncodingException e) {
            System.err.println("The OS does not support " + encoding);
            e.printStackTrace();
            return null;
        }
    }

    public int execRootCmdSilent(String cmd) {
        int result = -1;
        DataOutputStream dos = null;
        try {
            Process p = Runtime.getRuntime().exec("su");
            dos = new DataOutputStream(p.getOutputStream());
            Log.i(TAG, cmd);
            dos.writeBytes(cmd + "\n");
            dos.flush();
            dos.writeBytes("exit\n");
            dos.flush();
            p.waitFor();
            result = p.exitValue();
            Log.i(TAG, "Success execRootCmdSilent(" + cmd + ")=" + result);
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG,
                    "execRootCmdSilent(" + cmd + "),Exception:"
                            + e.getMessage());
        } finally {
            if (dos != null) {
                try {
                    dos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    public String getFromAssets(String fileName) {
        try {
            InputStreamReader inputReader = new InputStreamReader(getResources().getAssets().open(fileName));
            BufferedReader bufReader = new BufferedReader(inputReader);
            String line = "";
            String Result = "";
            while ((line = bufReader.readLine()) != null)
                Result += line;
            return Result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
